package es.unex.meigas.ww.gui;

import java.util.ArrayList;

import es.unex.meigas.dataObjects.AbstractInputFactory;
import es.unex.meigas.dataObjects.IDataObject;
import es.unex.meigas.ww.core.WWRasterLayer;
import es.unex.meigas.ww.core.WWVectorLayer;
import es.unex.sextante.core.NamedExtent;
import es.unex.sextante.gui.core.SextanteGUI;
import es.unex.sextante.ww.app.FileTools;
import es.unex.sextante.ww.app.SextanteWind;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.layers.Layer;
import gov.nasa.worldwind.layers.LayerList;
import gw.layers.GridCoverageLayer;
import gw.layers.SimpleFeatureLayer;

public class WWInputFactory extends AbstractInputFactory {

	WorldWindow m_WorldWindow = null;

	public WWInputFactory(WorldWindow ww) {

		m_WorldWindow = ww;

	}

	public void createDataObjects() {

		IDataObject obj;
		ArrayList layers = new ArrayList();
		LayerList layerList = m_WorldWindow.getModel().getLayers();

		for (int i = 0; i < layerList.size(); i++) {
			Layer layer = layerList.get(i);
			if (layer instanceof SimpleFeatureLayer){
				obj = new WWVectorLayer();
				((WWVectorLayer)obj).create((SimpleFeatureLayer)layer);
				layers.add(obj);
			}
			else if (layer instanceof GridCoverageLayer){
				obj = new WWRasterLayer();
				((WWRasterLayer)obj).create((GridCoverageLayer)layer);
				layers.add(obj);
			}
		}

		m_Objects = new IDataObject[layers.size()];
		for (int i = 0; i < layers.size(); i++) {
			m_Objects[i] = (IDataObject) layers.get(i);
		}

	}


	public NamedExtent[] getPredefinedExtents() {

		return new NamedExtent[0];

	}

	public String[] getRasterLayerInputExtensions() {

		return new String[]{"tif"};

	}

	public String[] getTableInputExtensions() {

		return new String[]{"dbf"};

	}

	public String[] getVectorLayerInputExtensions() {

		return new String[]{"shp"};

	}


	public void close(String sName) {

		/////TODO

	}

	public IDataObject openDataObjectFromFile(String sFilename) {

		Object  obj = FileTools.openFile(sFilename, m_WorldWindow);
		if (obj == null){
			return null;
		}

		if (obj instanceof GridCoverageLayer) {
			GridCoverageLayer glc = (GridCoverageLayer) obj;
			WWRasterLayer returnLayer = new WWRasterLayer();
			returnLayer.create(glc);
			return returnLayer;
		}
		else if (obj instanceof SimpleFeatureLayer){
			SimpleFeatureLayer sfl = (SimpleFeatureLayer) obj;
			WWVectorLayer returnLayer = new WWVectorLayer();
			returnLayer.create(sfl);
			return returnLayer;
		}
		else{
			return null;
		}

	}

	public void addDataObjectToGIS(IDataObject obj){

		Layer layer = (Layer) obj.getBaseDataObject();
		if (layer instanceof SimpleFeatureLayer){
			((SimpleFeatureLayer)layer).redraw();
		}
		this.m_WorldWindow.getModel().getLayers().add(layer);
        layer.setPickEnabled(false);
    	SextanteWind.updateTOC();

	}

}
